package com.huluobo.a2206monthdemo.video;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2206monthdemo.R;
import com.huluobo.a2206monthdemo.adapter.CommentAdapter;
import com.huluobo.a2206monthdemo.adapter.MultiVideoAdapter;
import com.huluobo.a2206monthdemo.databinding.FragmentVideoBinding;
import com.huluobo.a2206monthdemo.live.LiveActivity;
import com.huluobo.a2206monthdemo.login.LoginActivity;
import com.huluobo.base.bean.VideoBeanResult;
import com.huluobo.base.db.AppDBUtils;
import com.huluobo.base.mvvm.BaseMVVMFragment;
import com.huluobo.base.net.Const;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;


public class VideoFragment extends BaseMVVMFragment<FragmentVideoBinding, VideoViewModel> {
    private MultiVideoAdapter videoAdapter;
    private int currentPosition = 0;
    private StandardGSYVideoPlayer player;
    private CommentAdapter commentAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_video;
    }

    @Override
    protected void initData() {
        viewModel.getVideoList(2, 10);

        viewModel.getVideoListSuccess.observe(this, videoBeanResult -> {
            if (videoBeanResult.getCode() == 200) {
                videoAdapter.getData().clear();
                videoAdapter.getData().addAll(videoBeanResult.getData());
                videoAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(videoBeanResult.getMessage());
            }
        });

        viewModel.getVideoListFailed.observe(this, s -> {
            Log.i("TagA", "获取视频列表失败:" + s);
        });

        viewModel.likeVideoSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoAdapter.getData().get(currentPosition).setDianzan(1);
                videoAdapter.notifyDataSetChanged();
            }
        });

        viewModel.likeVideoFailed.observe(this, s -> {
            Log.i("TagA", "点赞失败:" + s);
        });

        viewModel.noLikeVideoSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoAdapter.getData().get(currentPosition).setDianzan(0);
                videoAdapter.notifyDataSetChanged();
            }
        });

        viewModel.noLikeVideoFailed.observe(this, s -> {
            Log.i("TagA", "取消点赞失败:" + s);
        });

        viewModel.followAuthSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoAdapter.getData().get(currentPosition).setGuanzhu(1);
                videoAdapter.notifyDataSetChanged();
            }
        });

        viewModel.followAuthFailed.observe(this, s -> {
            Log.i("TagA", "关注失败:" + s);
        });

        viewModel.getCommentSuccess.observe(this, commentBeanResult -> {
            if (commentBeanResult.getCode() == 200) {
                commentAdapter.getData().clear();
                commentAdapter.getData().addAll(commentBeanResult.getData());
                commentAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(commentBeanResult.getMessage());
            }
        });

        viewModel.getCommentFailed.observe(this, s -> {
            Log.i("TagA", "获取评论失败:" + s);
        });

        viewModel.sendCommentSuccess.observe(this, commentBeanResult -> {
            if (commentBeanResult.getCode() == 200) {
                commentAdapter.getData().addAll(0, commentBeanResult.getData());
                commentAdapter.notifyDataSetChanged();

                EditText editText = (EditText) videoAdapter.getViewByPosition(currentPosition,
                        R.id.item_videos_comment_et);
                editText.setText("");
            } else {
                ToastUtils.showLong(commentBeanResult.getMessage());
            }
        });

        viewModel.sendCommentFailed.observe(this, s -> {
            Log.i("TagA", "发送评论失败:" + s);
        });
    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        binding.videosRv.setLayoutManager(layoutManager);
        videoAdapter = new MultiVideoAdapter();
        binding.videosRv.setAdapter(videoAdapter);

        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(binding.videosRv);

        binding.videosRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                currentPosition = layoutManager.findFirstVisibleItemPosition();
                player = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(currentPosition,
                        R.id.item_videos_gsyPlayer);
                if (player != null) {
//                    player.startPlayLogic();
                }
            }
        });

        videoAdapter.addChildClickViewIds(R.id.item_videos_like_iv, R.id.item_videos_add_iv,
                R.id.item_videos_comment_iv, R.id.item_videos_close_iv, R.id.item_videos_comment_send_iv,
                R.id.item_videos_share_iv, R.id.item_videos_collect_iv, R.id.item_videos_live_cl,
                R.id.item_videos_full_cl);
        videoAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            VideoBeanResult.VideoBean videoBean = (VideoBeanResult.VideoBean) adapter.getData().get(position);
            String token = SPUtils.getInstance().getString(Const.PARAM_TOKEN);
            if (token.isEmpty()) {
                startActivity(new Intent(requireContext(), LoginActivity.class));
                return;
            }
            switch (view.getId()) {
                case R.id.item_videos_like_iv:
                    likeVideo(videoBean);
                    break;
                case R.id.item_videos_add_iv:
                    followAuth(videoBean);
                    break;
                case R.id.item_videos_comment_iv:
                    openComment(videoBean);
                    break;
                case R.id.item_videos_close_iv:
                    closeComment(videoBean);
                    break;
                case R.id.item_videos_comment_send_iv:
                    sendComment(videoBean);
                    break;
                case R.id.item_videos_share_iv:
                    shareVideo(videoBean);
                    break;
                case R.id.item_videos_collect_iv:
                    collectVideo(videoBean);
                    break;
                case R.id.item_videos_full_cl:
                    fullScreen(videoBean);
                    break;
                case R.id.item_videos_live_cl:
                    toLive(videoBean);
                    break;
            }
        });
    }

    private void toLive(VideoBeanResult.VideoBean videoBean) {
        Intent intent = new Intent(requireContext(), LiveActivity.class);
        intent.putExtra("videoBean", videoBean);
        startActivity(intent);
    }

    private void fullScreen(VideoBeanResult.VideoBean videoBean) {
        if (player != null) {
            player.setRotateViewAuto(true);
            player.startWindowFullscreen(requireContext(), false, false);
            player.startPlayLogic();
        }
    }

    private void collectVideo(VideoBeanResult.VideoBean videoBean) {
        AppDBUtils.getInstance().getVideoDao().insertVideoInfo(videoBean);
        ToastUtils.showLong("收藏成功");
    }

    private void shareVideo(VideoBeanResult.VideoBean videoBean) {
        UMImage umImage = new UMImage(requireContext(), videoBean.getVideomainimg());
        umImage.compressStyle = UMImage.CompressStyle.SCALE;

        UMWeb web = new UMWeb(videoBean.getVideopath());
        web.setThumb(umImage);
        web.setTitle(videoBean.getAuthname());
        web.setDescription(videoBean.getCaption());

        new ShareAction(requireActivity())
                .withMedia(web)
                .open();
    }

    private void sendComment(VideoBeanResult.VideoBean videoBean) {
        EditText editText = (EditText) videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et);
        String msg = editText.getText().toString();
        if (msg.isEmpty()) {
            ToastUtils.showLong("评论内容不能为空");
        } else {
            viewModel.sendComment(videoBean.getId(), msg);
        }
    }

    private void closeComment(VideoBeanResult.VideoBean videoBean) {
        View commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll);
        commentLayout.setVisibility(View.VISIBLE);
        Animation animationOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out);
        animationOut.setDuration(500);
        commentLayout.startAnimation(animationOut);
        animationOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                commentLayout.setVisibility(View.GONE);
                binding.videosRv.setIntercept(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void openComment(VideoBeanResult.VideoBean videoBean) {
        binding.videosRv.setIntercept(false);
        View commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll);
        commentLayout.setVisibility(View.VISIBLE);
        Animation animationIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in);
        animationIn.setDuration(500);
        commentLayout.startAnimation(animationIn);

        RecyclerView commentRv = (RecyclerView) videoAdapter.getViewByPosition(currentPosition,
                R.id.item_videos_comment_rv);
        commentRv.setLayoutManager(new LinearLayoutManager(requireContext()));
        commentAdapter = new CommentAdapter();
        commentRv.setAdapter(commentAdapter);

        animationIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                viewModel.getComment(videoBean.getId());
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void followAuth(VideoBeanResult.VideoBean videoBean) {
        viewModel.followAuth(videoBean.getAuthname());
    }

    private void likeVideo(VideoBeanResult.VideoBean videoBean) {
        if (videoBean.getDianzan() == 0) {
            viewModel.likeVideo(videoBean.getId());
        } else {
            viewModel.noLikeVideo(videoBean.getId());
        }
    }

    @Override
    protected Class<VideoViewModel> getViewModel() {
        return VideoViewModel.class;
    }
}